<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>图片提取功能测试</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
        }
        
        .container {
            max-width: 900px;
            margin: 0 auto;
            background: white;
            border-radius: 15px;
            padding: 30px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.1);
        }
        
        h1 {
            color: #333;
            text-align: center;
            margin-bottom: 20px;
            font-size: 2rem;
        }
        
        .description {
            background: #e7f3ff;
            border-left: 4px solid #2196F3;
            padding: 15px;
            margin-bottom: 20px;
            border-radius: 0 8px 8px 0;
        }
        
        .file-section {
            border: 2px dashed #667eea;
            border-radius: 10px;
            padding: 20px;
            text-align: center;
            margin-bottom: 20px;
            background: #f8f9ff;
        }
        
        .file-input {
            margin: 15px 0;
        }
        
        .file-input input[type="file"] {
            display: none;
        }
        
        .file-input label {
            display: inline-block;
            padding: 12px 24px;
            background: #667eea;
            color: white;
            border-radius: 8px;
            cursor: pointer;
            transition: background 0.3s ease;
            font-weight: 500;
        }
        
        .file-input label:hover {
            background: #5a6fd8;
        }
        
        .button {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 12px 24px;
            border: none;
            border-radius: 8px;
            cursor: pointer;
            font-size: 16px;
            margin: 10px 5px;
            transition: all 0.3s ease;
            font-weight: 500;
        }
        
        .button:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(102, 126, 234, 0.4);
        }
        
        .button:disabled {
            background: #ccc;
            cursor: not-allowed;
            transform: none;
            box-shadow: none;
        }
        
        .result {
            margin-top: 20px;
            padding: 15px;
            border-radius: 8px;
            background-color: #f8f9fa;
            border-left: 4px solid #667eea;
            font-family: 'Courier New', monospace;
            font-size: 13px;
            max-height: 200px;
            overflow-y: auto;
        }
        
        .loading {
            display: none;
            text-align: center;
            padding: 20px;
        }
        
        .spinner {
            border: 3px solid #f3f3f3;
            border-top: 3px solid #667eea;
            border-radius: 50%;
            width: 30px;
            height: 30px;
            animation: spin 1s linear infinite;
            margin: 0 auto 10px;
        }
        
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
        
        .preview-container {
            margin-top: 30px;
            display: none;
        }
        
        .preview-title {
            color: #333;
            font-size: 1.2rem;
            margin-bottom: 15px;
            text-align: center;
        }
        
        .preview-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(180px, 1fr));
            gap: 20px;
            max-height: 500px;
            overflow-y: auto;
            padding: 10px;
            border: 1px solid #e1e5e9;
            border-radius: 8px;
            background: #fafafa;
        }
        
        .stats {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
            gap: 15px;
            margin: 20px 0;
        }
        
        .stat-item {
            background: linear-gradient(135deg, #fff 0%, #f8f9fa 100%);
            padding: 15px;
            border-radius: 8px;
            text-align: center;
            border: 1px solid #e1e5e9;
        }
        
        .stat-number {
            font-size: 1.5rem;
            font-weight: bold;
            color: #667eea;
        }
        
        .stat-label {
            font-size: 0.9rem;
            color: #666;
            margin-top: 5px;
        }
        
        /* 导航栏样式 */
        .navbar {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            padding: 1rem 0;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            margin-bottom: 2rem;
        }
        
        .nav-container {
            max-width: 1200px;
            margin: 0 auto;
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 0 2rem;
        }
        
        .nav-brand {
            color: white;
            font-size: 1.5rem;
            font-weight: bold;
            text-decoration: none;
        }
        
        .nav-links {
            display: flex;
            gap: 1rem;
            list-style: none;
            margin: 0;
            padding: 0;
        }
        
        .nav-link {
            color: white;
            text-decoration: none;
            padding: 0.5rem 1rem;
            border-radius: 4px;
            transition: background-color 0.3s ease;
        }
        
        .nav-link:hover {
            background-color: rgba(255, 255, 255, 0.2);
        }
        
        .nav-link.active {
            background-color: rgba(255, 255, 255, 0.3);
        }
        
        /* 移动端导航适配 */
        @media (max-width: 768px) {
            .nav-container {
                flex-direction: column;
                gap: 1rem;
                padding: 0 1rem;
            }
            
            .nav-links {
                flex-wrap: wrap;
                justify-content: center;
            }
            
            .nav-link {
                font-size: 0.9rem;
                padding: 0.4rem 0.8rem;
            }
        }
        
        /* 按钮组样式 */
        .button-group {
            display: flex;
            gap: 10px;
            flex-wrap: wrap;
            justify-content: center;
            margin-top: 15px;
        }
        
        .btn-secondary {
            background: linear-gradient(135deg, #28a745 0%, #20c997 100%);
        }
        
        .btn-secondary:hover {
            background: linear-gradient(135deg, #218838 0%, #1e7e34 100%);
        }
    </style>
</head>
<body>
    <!-- 导航栏 -->
    <nav class="navbar">
        <div class="nav-container">
            <a href="/" class="nav-brand">Excel Demo</a>
            <ul class="nav-links">
                <li><a href="/" class="nav-link">🏠 主页</a></li>
                <li><a href="/test_downloads.html" class="nav-link">📤 异步导出测试</a></li>
                <li><a href="/test_image.html" class="nav-link">🖼️ 图片压缩测试</a></li>
                <li><a href="/test_easyexcel_import.html" class="nav-link">📋 EasyExcel图片导入测试</a><li>
            </ul>
        </div>
    </nav>
    
    <div class="container">
        <h1>🖼️ 图片提取功能测试</h1>
        
        <div class="description">
            <h3>🌟 功能说明：</h3>
            <p>此功能将从Excel文件中智能识别并提取所有嵌入图片，保存到<code>output/readImage</code>目录中，并支持实时预览和模态框查看。</p>
            <ul style="margin: 10px 0; padding-left: 20px;">
                <li>支持.xlsx和.xls格式</li>
                <li>自动识别图片位置和格式</li>
                <li>实时预览提取的图片</li>
                <li>点击图片放大查看</li>
                <li>支持ESC键关闭模态框</li>
            </ul>
        </div>

        <div class="file-section">
            <h3>📁 选择Excel文件</h3>
            <p style="color: #666; margin: 10px 0;">支持包含图片的Excel文件</p>
            
            <div class="file-input">
                <label for="excelFile">
                    <span id="fileLabel">📄 选择Excel文件</span>
                </label>
                <input type="file" id="excelFile" accept=".xlsx,.xls" onchange="updateFileLabel()">
            </div>
            
            <div class="button-group">
                <button class="button" onclick="testImageExtraction()" id="extractBtn">
                    🔍 提取图片
                </button>
                
                <button class="button btn-secondary" onclick="downloadTemplate()" id="downloadBtn">
                    📅 下载图片模板
                </button>
            </div>
        </div>

        <div class="loading" id="loading">
            <div class="spinner"></div>
            <p>正在处理Excel文件并提取图片，请稍候...</p>
        </div>

        <div id="stats" class="stats" style="display: none;">
            <div class="stat-item">
                <div class="stat-number" id="imageCount">0</div>
                <div class="stat-label">提取图片数量</div>
            </div>
            <div class="stat-item">
                <div class="stat-number" id="totalSize">0 KB</div>
                <div class="stat-label">总文件大小</div>
            </div>
            <div class="stat-item">
                <div class="stat-number" id="processTime">0s</div>
                <div class="stat-label">处理时间</div>
            </div>
        </div>

        <div id="result" class="result" style="display: none;"></div>

        <div id="imagePreviewContainer" class="preview-container">
            <h3 class="preview-title">📸 提取的图片预览</h3>
            <div id="imagePreviewGrid" class="preview-grid"></div>
        </div>
    </div>

    <script>
        let startTime;
        
        function updateFileLabel() {
            const fileInput = document.getElementById('excelFile');
            const fileLabel = document.getElementById('fileLabel');
            
            if (fileInput.files.length > 0) {
                const fileName = fileInput.files[0].name;
                fileLabel.textContent = `📄 ${fileName}`;
            } else {
                fileLabel.textContent = '📄 选择Excel文件';
            }
        }
        
        // 下载图片Excel模板
        function downloadTemplate() {
            const downloadBtn = document.getElementById('downloadBtn');
            
            try {
                downloadBtn.disabled = true;
                downloadBtn.textContent = '下载中...';
                
                // 直接打开下载链接
                window.open('/api/image/template/download/stream', '_blank');
                
                // 显示成功提示
                setTimeout(() => {
                    alert('图片Excel模板下载已开始，请检查浏览器下载目录。');
                }, 500);
                
            } catch (error) {
                console.error('下载模板失败:', error);
                alert('下载模板失败：' + error.message);
            } finally {
                downloadBtn.disabled = false;
                downloadBtn.textContent = '📅 下载图片模板';
            }
        }

        async function testImageExtraction() {
            const fileInput = document.getElementById('excelFile');
            const loading = document.getElementById('loading');
            const result = document.getElementById('result');
            const previewContainer = document.getElementById('imagePreviewContainer');
            const extractBtn = document.getElementById('extractBtn');
            const stats = document.getElementById('stats');
            
            if (!fileInput.files[0]) {
                alert('请先选择Excel文件');
                return;
            }

            startTime = Date.now();
            const formData = new FormData();
            formData.append('file', fileInput.files[0]);

            try {
                // 显示加载状态
                loading.style.display = 'block';
                extractBtn.disabled = true;
                extractBtn.textContent = '处理中...';
                result.style.display = 'none';
                previewContainer.style.display = 'none';
                stats.style.display = 'none';
                
                const response = await fetch('/api/image/extract/excel', {
                    method: 'POST',
                    body: formData
                });
                
                const responseData = await response.json();
                
                // 添加详细的调试信息
                console.log('API响应数据:', responseData);
                console.log('响应状态:', response.status);
                console.log('响应code字段:', responseData.code);
                console.log('响应msg字段:', responseData.msg);
                if (responseData.data) {
                    console.log('数据对象:', responseData.data);
                    console.log('图片数组:', responseData.data.images);
                    console.log('图片数量:', responseData.data.images ? responseData.data.images.length : 0);
                }
                
                // 显示原始响应结果
                result.innerHTML = `<pre>${JSON.stringify(responseData, null, 2)}</pre>`;
                result.style.display = 'block';
                
                // 修正的响应数据判断逻辑：R类使用code=0表示成功
                if (responseData.code === 0) {
                    if (responseData.data && responseData.data.images && Array.isArray(responseData.data.images)) {
                        const imageCount = responseData.data.images.length;
                        console.log('检测到图片数量:', imageCount);
                        
                        if (imageCount > 0) {
                            // 显示统计信息
                            const processTime = ((Date.now() - startTime) / 1000).toFixed(1);
                            document.getElementById('imageCount').textContent = imageCount;
                            document.getElementById('processTime').textContent = processTime + 's';
                            stats.style.display = 'grid';
                            
                            // 计算总大小（异步）
                            calculateTotalSize(responseData.data.images);
                            
                            // 显示图片预览
                            displayImagePreviews(responseData.data.images);
                            console.log('图片预览显示完成');
                        } else {
                            alert('Excel文件中未发现任何图片');
                            console.warn('Excel文件中未发现图片');
                        }
                    } else {
                        alert('响应数据格式异常：缺少images数组');
                        console.error('响应数据格式异常:', responseData);
                    }
                } else {
                    const errorMsg = responseData.msg || '图片提取失败';
                    alert('提取失败: ' + errorMsg);
                    console.error('API返回失败状态:', responseData);
                }
                
            } catch (error) {
                result.innerHTML = `<pre>错误: ${error.message}</pre>`;
                result.style.display = 'block';
                alert('提取图片时发生错误: ' + error.message);
            } finally {
                loading.style.display = 'none';
                extractBtn.disabled = false;
                extractBtn.textContent = '🔍 提取图片';
            }
        }
        
        async function calculateTotalSize(imagePaths) {
            let totalSize = 0;
            for (const imagePath of imagePaths) {
                try {
                    const response = await fetch(`/api/image/info?filePath=${encodeURIComponent(imagePath)}`);
                    const data = await response.json();
                    // 使用code=0判断成功
                    if (data.code === 0 && data.data) {
                        totalSize += data.data.fileSizeKB;
                    }
                } catch (error) {
                    console.warn('获取文件大小失败:', error);
                }
            }
            
            const totalSizeDisplay = totalSize > 1024 ? 
                `${(totalSize / 1024).toFixed(1)} MB` : 
                `${Math.round(totalSize)} KB`;
            document.getElementById('totalSize').textContent = totalSizeDisplay;
        }
        
        function displayImagePreviews(imagePaths) {
            const previewContainer = document.getElementById('imagePreviewContainer');
            const previewGrid = document.getElementById('imagePreviewGrid');
            
            // 清空之前的预览内容
            previewGrid.innerHTML = '';
            
            if (!imagePaths || imagePaths.length === 0) {
                previewContainer.style.display = 'none';
                return;
            }
            
            // 更新预览标题，显示图片数量
            const previewTitle = previewContainer.querySelector('.preview-title');
            previewTitle.textContent = `📸 提取的图片预览 (${imagePaths.length}张图片)`;
            
            imagePaths.forEach((imagePath, index) => {
                const imageItem = document.createElement('div');
                imageItem.style.cssText = `
                    border: 2px solid #e1e5e9;
                    border-radius: 8px;
                    padding: 10px;
                    text-align: center;
                    background: #f8f9fa;
                    transition: all 0.3s ease;
                    position: relative;
                `;
                
                // 创建加载状态指示器
                const loadingIndicator = document.createElement('div');
                loadingIndicator.style.cssText = `
                    display: flex;
                    justify-content: center;
                    align-items: center;
                    height: 120px;
                    color: #666;
                    font-size: 12px;
                `;
                loadingIndicator.textContent = '加载中...';
                imageItem.appendChild(loadingIndicator);
                
                // 创建图片元素
                const img = document.createElement('img');
                img.style.cssText = `
                    width: 100%;
                    height: 120px;
                    object-fit: cover;
                    border-radius: 4px;
                    margin-bottom: 8px;
                    cursor: pointer;
                    display: none;
                `;
                
                // 提取文件名（从完整路径中提取）
                const fileName = imagePath.split('/').pop() || imagePath.split('\\').pop();
                
                // 使用查询参数方式访问图片，传递完整的相对路径
                const imageUrl = `/api/image/view?imagePath=${encodeURIComponent(imagePath)}`;
                img.src = imageUrl;
                img.alt = `提取的图片 ${index + 1}`;
                
                // 图片加载成功处理
                img.onload = function() {
                    loadingIndicator.style.display = 'none';
                    img.style.display = 'block';
                    console.log(`图片加载成功: ${fileName}`);
                    
                    // 添加加载成功的视觉反馈
                    imageItem.style.borderColor = '#28a745';
                    setTimeout(() => {
                        imageItem.style.borderColor = '#e1e5e9';
                    }, 1000);
                };
                
                // 图片加载错误处理
                img.onerror = function() {
                    loadingIndicator.style.display = 'none';
                    const errorDiv = document.createElement('div');
                    errorDiv.style.cssText = `
                        color: #dc3545;
                        font-size: 12px;
                        padding: 20px;
                        background: #f8d7da;
                        border-radius: 4px;
                        height: 120px;
                        display: flex;
                        align-items: center;
                        justify-content: center;
                        flex-direction: column;
                    `;
                    errorDiv.innerHTML = `
                        <span>❌ 图片加载失败</span>
                        <span style="font-size: 10px; margin-top: 5px;">${fileName}</span>
                    `;
                    imageItem.appendChild(errorDiv);
                    
                    // 错误状态的视觉反馈
                    imageItem.style.borderColor = '#dc3545';
                };
                
                // 点击放大查看
                img.onclick = function() {
                    showImageModal(imageUrl, fileName, index + 1);
                };
                
                // 文件名显示
                const fileNameDiv = document.createElement('div');
                fileNameDiv.textContent = fileName;
                fileNameDiv.style.cssText = `
                    font-size: 11px;
                    color: #666;
                    word-break: break-all;
                    line-height: 1.2;
                    margin-top: 5px;
                `;
                
                // 文件信息显示
                const fileInfoDiv = document.createElement('div');
                fileInfoDiv.style.cssText = `
                    font-size: 10px;
                    color: #999;
                    margin-top: 2px;
                `;
                
                // 异步获取文件信息
                getImageFileInfo(imagePath, fileInfoDiv);
                
                imageItem.appendChild(img);
                imageItem.appendChild(fileNameDiv);
                imageItem.appendChild(fileInfoDiv);
                
                // 鼠标悬停效果
                imageItem.onmouseenter = function() {
                    if (this.style.borderColor !== 'rgb(220, 53, 69)') { // 不是错误状态
                        this.style.borderColor = '#667eea';
                        this.style.transform = 'translateY(-2px)';
                        this.style.boxShadow = '0 5px 15px rgba(102, 126, 234, 0.2)';
                    }
                };
                
                imageItem.onmouseleave = function() {
                    if (this.style.borderColor !== 'rgb(220, 53, 69)') { // 不是错误状态
                        this.style.borderColor = '#e1e5e9';
                        this.style.transform = 'translateY(0)';
                        this.style.boxShadow = 'none';
                    }
                };
                
                previewGrid.appendChild(imageItem);
            });
            
            previewContainer.style.display = 'block';
        }
        
        // 显示图片模态框
        function showImageModal(imageUrl, fileName, imageIndex) {
            const modal = document.createElement('div');
            modal.style.cssText = `
                position: fixed;
                top: 0;
                left: 0;
                width: 100%;
                height: 100%;
                background: rgba(0,0,0,0.9);
                display: flex;
                justify-content: center;
                align-items: center;
                z-index: 1000;
                cursor: pointer;
                opacity: 0;
                transition: opacity 0.3s ease;
            `;
            
            const modalContent = document.createElement('div');
            modalContent.style.cssText = `
                max-width: 90%;
                max-height: 90%;
                text-align: center;
                cursor: default;
            `;
            
            const modalImg = document.createElement('img');
            modalImg.src = imageUrl;
            modalImg.style.cssText = `
                max-width: 100%;
                max-height: 80vh;
                border-radius: 8px;
                box-shadow: 0 10px 30px rgba(0,0,0,0.5);
            `;
            
            const modalTitle = document.createElement('div');
            modalTitle.textContent = `图片 ${imageIndex}: ${fileName}`;
            modalTitle.style.cssText = `
                color: white;
                font-size: 14px;
                margin-top: 10px;
                padding: 5px 10px;
                background: rgba(0,0,0,0.7);
                border-radius: 4px;
                display: inline-block;
            `;
            
            const closeButton = document.createElement('div');
            closeButton.textContent = '✕';
            closeButton.style.cssText = `
                position: absolute;
                top: 20px;
                right: 30px;
                color: white;
                font-size: 24px;
                cursor: pointer;
                background: rgba(0,0,0,0.5);
                width: 40px;
                height: 40px;
                border-radius: 50%;
                display: flex;
                justify-content: center;
                align-items: center;
                transition: background 0.3s ease;
            `;
            
            closeButton.onmouseover = function() {
                this.style.background = 'rgba(255,255,255,0.2)';
            };
            
            closeButton.onmouseout = function() {
                this.style.background = 'rgba(0,0,0,0.5)';
            };
            
            modalContent.appendChild(modalImg);
            modalContent.appendChild(modalTitle);
            modal.appendChild(modalContent);
            modal.appendChild(closeButton);
            document.body.appendChild(modal);
            
            // 淡入效果
            setTimeout(() => {
                modal.style.opacity = '1';
            }, 10);
            
            // 关闭事件
            const closeModal = function() {
                modal.style.opacity = '0';
                setTimeout(() => {
                    if (modal.parentNode) {
                        document.body.removeChild(modal);
                    }
                }, 300);
            };
            
            modal.onclick = closeModal;
            closeButton.onclick = closeModal;
            modalContent.onclick = function(e) {
                e.stopPropagation(); // 防止点击图片关闭模态框
            };
            
            // ESC键关闭
            const handleKeyDown = function(e) {
                if (e.key === 'Escape') {
                    closeModal();
                    document.removeEventListener('keydown', handleKeyDown);
                }
            };
            document.addEventListener('keydown', handleKeyDown);
        }
        
        // 获取图片文件信息
        async function getImageFileInfo(imagePath, infoDiv) {
            try {
                const response = await fetch(`/api/image/info?filePath=${encodeURIComponent(imagePath)}`);
                const data = await response.json();
                
                // 使用code=0判断成功
                if (data.code === 0 && data.data) {
                    const sizeKB = Math.round(data.data.fileSizeKB);
                    const sizeDisplay = sizeKB > 1024 ? 
                        `${(sizeKB / 1024).toFixed(1)} MB` : 
                        `${sizeKB} KB`;
                    infoDiv.textContent = sizeDisplay;
                } else {
                    infoDiv.textContent = '大小未知';
                }
            } catch (error) {
                console.warn('获取文件信息失败:', error);
                infoDiv.textContent = '大小未知';
            }
        }
    </script>
</body>
</html>